import { ActionContext, createStore } from "vuex";
import templates, { TemplatesProps } from "./template";
import user, { UserProps } from "./user";
import editor, { EditorProps } from "./editor";
import global,{GlobalStatus} from "./global";
import axios, { AxiosRequestConfig } from "axios";
import { compile } from 'path-to-regexp';
import {objToQueryString} from '@/helper'
export interface GlobalDataProps {
  user: UserProps;
  templates: TemplatesProps;
  editor: EditorProps;
  global: GlobalStatus;
}

const store = createStore<GlobalDataProps>({
  modules: {
    user,
    templates,
    editor,
    global,
  },
});

export default store;

export interface ActionPayload{
  urlParams? :  { [key: string]: any };
  data?: any;
  searchParams?: { [key: string]: any };
}

//确定参数
// 第一步 先返回一个函数和原函数的处理一样
export function actionWrapper(url: string, commitName: string, config: AxiosRequestConfig = {method: 'get'}){
  return async (context: ActionContext<any, any>, payload: ActionPayload = {}) => {
    const {urlParams, data, searchParams} = payload;
    const newConfig = { ...config, data, opName:  commitName }; //在axios的拦截器会获取这个值
    let newUrl = url;
    if(urlParams){
      const toPath  = compile(url, {encode: encodeURIComponent});
      newUrl = toPath(urlParams);
      // console.log('actionWrapper',newUrl);
    }
    if(searchParams){
      const queryString = objToQueryString(searchParams);
      console.log('actionWrapper',searchParams, queryString);
      newUrl = `${newUrl}?${queryString}`;
    }
    const {data: res} = await axios(newUrl, newConfig);
    // console.log('actionWrapper',payload, res, commitName);
    context.commit(commitName, { payload, ...res});
    return res;
  };
}

